layui.use(['form', 'layer', 'table', 'laytpl'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;

    var userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'));
    var isAdmin = !!userInfo && userInfo.roleId == 3;
    var isAgent = !!userInfo && userInfo.roleId == 4;

    var cols = [
        { type: "checkbox", fixed: "left", width: 50 },
        { field: "Id", title: 'Id', width: 70, align: "center" },
        { field: 'UserName', title: '登陆ID', minWidth: 30, align: "center" },
        { field: 'RealName', title: '用户名', minWidth: 30, align: "center" },
        { field: 'ParentRealName', title: '上级代理', minWidth: 30, align: "center" },
        //{ field: 'NickName', title: '用户昵称', minWidth: 50, align: "center" },
        { field: 'Mobile', title: '手机号码', minWidth: 50, align: "center" },
        { field: 'Email', title: '邮箱地址', minWidth: 50, align: "center" },
        { field: 'RoleName', title: '所属角色', minWidth: 40, align: 'center' },
        { field: 'AddTime', title: '开户时间', minWidth: 40, align: 'center' },
        {
            field: 'State', title: '状态', minWidth: 100, fixed: "right", align: "left", templet: function (item) {
                var result = '';
                if (item.State == 1) {
                    if (item.IsLock && isAdmin) {
                        result += '<strong>视频认证: </strong>';
                        result += '<input type="checkbox" name="IsLock" value="' + item.Id + '" lay-filter="IsLock" lay-skin="switch" lay-text="是|否">';
                        result += '&nbsp;&nbsp;<a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="resetApply">重申</a>';
                    } else if (item.IsLock && !isAdmin) {
                        result += '<a class="layui-btn layui-btn-xs layui-btn-warm">审核中</a>';
                    } else {
                        result += '<a class="layui-btn layui-btn-xs">&nbsp;&nbsp;通过&nbsp;&nbsp;</a>';
                    }
                } else if (item.State == 2) {
                    result += '<a class="layui-btn layui-btn-xs layui-btn-disabled">不通过</a>&nbsp;';
                    result += '<i class="layui-icon" lay-event="audit_remark" title="驳回原因">&#xe60b;</i>';
                    if (isAdmin) result += '<a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="resetApply">重申</a>';
                } else {
                    result += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="state">未审核</a>';
                    if (isAdmin) result += '<a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="resetApply">重申</a>';
                }
                if (isAgent) {
                    result += ' <a class="layui-btn layui-btn-xs" lay-event="preview">查看</a>';
                }
                return result;
            }
        }
    ];
    if (isAdmin) {
        cols.push({
            title: '操作', minWidth: 120, fixed: "right", align: "left", templet: function (item) {
                var result = '<a class="layui-btn layui-btn-sm" lay-event="preview">查看</a>';
                if (item.State == 1 && !item.IsLock) {
                    result += '<a class="layui-btn layui-btn-sm layui-btn-green" lay-event="trade">手续费</a>';
                }
                result += '<a class="layui-btn layui-btn-sm layui-btn-danger" lay-event="resetpwd">重置密码</a>';
                return result;
            }
        });
    }

    //角色列表
    var tableIns = table.render({
        elem: '#managerList',
        url: '/Manager/LoadData/',
        cellMinWidth: 95,
        page: true,
        height: "full-125",
        limits: [10, 15, 20, 25],
        limit: 10,
        id: "managerListTable",
        cols: [cols]
    });
    
    if (isAdmin) $(".code_btn").show();

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click", function () {
        table.reload("managerListTable", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                key: $(".searchVal").val(),  //搜索的关键字
                state: $(".searchState").val(),
                roleId: $(".searchRoleId").val()
            }
        });
    });

    //添加用户
    function addManager(edit) {
        var tit = "添加用户";
        if (edit) {
            tit = "编辑用户";
        }
        var index = layui.layer.open({
            title: tit,
            type: 2,
            anim: 1,
            area: ['500px', '90%'],
            content: "/Manager/AddOrModify/",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    body.find("#Id").val(edit.Id);
                    body.find(".UserName").val(edit.UserName);
                    body.find(".NickName").val(edit.NickName);
                    body.find(".RoleId").val(edit.RoleId);
                    body.find(".Mobile").val(edit.Mobile);
                    body.find(".Email").val(edit.Email);
                    body.find("input:checkbox[name='IsLock']").prop("checked", edit.IsLock);
                    body.find(".Remark").text(edit.Remark || '');
                    form.render();
                }
            }
        });
    }

    function previewManager(edit) {
        var index = layui.layer.open({
            title: "查看用户",
            type: 2,
            anim: 1,
            area: ['500px', '90%'],
            content: "/Manager/Preview/",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    body.find("#Id").val(edit.Id);
                    body.find(".UserName").val(edit.UserName);
                    body.find(".RealName").val(edit.RealName);
                    body.find(".CardId").val(edit.CardId);
                    body.find(".RoleId").val(edit.RoleId);
                    //body.find(".Mobile").val(edit.Mobile);
                    //body.find(".Email").val(edit.Email);
                    body.find(".BankType").val(edit.BankType);
                    //body.find(".BankCard").val(edit.BankCard);
                    body.find(".AddTime").val(edit.AddTime);

                    DecryptManagerInfo(edit, function (res) {
                        body.find(".CardId").val(res.CardId);
                        body.find(".Mobile").val(res.Mobile);
                        body.find(".Email").val(res.Email);
                        body.find(".BankCard").val(res.BankCard);
                    });

                    var html = '';
                    for (var i = 0; i < edit.AuditImages.length; i++) {
                        var source = edit.AuditImages[i];
                        var src = 'http://dns.qsgjlive.com/' + source;
                        html += '<a target="_blank" href="' + src + '"><img src="' + src + '" style="width: 60px; height: 60px;margin: 2px;"></a>';
                    }
                    body.find(".auditImages").html(html);
                    body.find(".AuditRemark").text(edit.AuditRemark || '');
                    body.find(".Remark").text(edit.Remark || '');
                    form.render();
                }
            }
        });
    }

    function DecryptManagerInfo(edit, callback) {
        if (!isAdmin) {
            //获取防伪标记
            $.ajax({
                type: 'GET',
                url: '/Manager/DecryptManagerInfo/',
                data: {
                    managerId: edit.Id
                },
                dataType: "json",
                success: function (res) {//res为相应体,function为回调函数
                    callback && callback(res);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
                }
            });
        } else {
            callback && callback(edit);
        }
    }
    ///查看审核原因
    function previewAduitRemark(edit) {
        var index = layui.layer.open({
            title: "查看原因",
            anim: 1,
            area: ['500px', '50%'],
            content: "<div style='height:70%;width:420px;padding:20px;border:0'>" + (edit.AuditRemark||'')+ "</div>",
            btn:false
        })
    }
    
    $(".addManager_btn").click(function () {
        addManager();
    });

    //批量删除
    $(".delAll_btn").click(function () {
        var checkStatus = table.checkStatus('managerListTable'),
            data = checkStatus.data,
            managerId = [];
        if (data.length > 0) {
            for (var i in data) {
                managerId.push(data[i].Id);
            }
            layer.confirm('确定删除选中的用户？', { icon: 3, title: '提示信息' }, function (index) {
                //获取防伪标记
                del(managerId);
            });
        } else {
            layer.msg("请选择需要删除的用户");
        }
    });

    // 我的二维码
    $(".code_btn").click(function () {
        mycode();
    });

    //列表操作
    table.on('tool(managerList)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;
        if (layEvent === 'preview') { //编辑
            previewManager(data);
        } else if (layEvent === 'trade') { //手续费
            settingTrade(data.Id);
        } else if (layEvent === 'edit') { //编辑
            addManager(data);
        } else if (layEvent === 'resetpwd') { //删除
            layer.confirm('此用户密码将被重置为初始密码，确定要重置？', { icon: 3, title: '提示信息' }, function (index) {
                resetpwd(data.Id);
            });
        } else if (layEvent === 'del') { //删除
            layer.confirm('确定删除此用户？', { icon: 3, title: '提示信息' }, function (index) {
                del(data.Id);
            });
        } else if (layEvent === 'state') {
            confirm_audit(data);
        } else if (layEvent == "audit_remark") {
            previewAduitRemark(data);
        } else if (layEvent == "resetApply") {
            if (isAdmin) {
                layer.confirm('确定要重申此用户吗？此操作会导致用户被删除', { icon: 3, title: '提示信息' }, function (index) {
                    resetApply(data.Id);

                });
            }
        }
    });

    form.on('switch(IsLock)', function (data) {
        if (isAdmin) {
            var tipText = '确定要通过此用户的视频认证吗？';
            if (!data.elem.checked) {
                tipText = '确定要通过此用户的视频认证吗？';
            }
            layer.confirm(tipText, {
                icon: 3,
                title: '系统提示',
                cancel: function (index) {
                    data.elem.checked = !data.elem.checked;
                    form.render();
                    layer.close(index);
                }
            }, function (index) {
                changeLockStatus(data.value, data.elem.checked);
                tableIns.reload();
                layer.close(index);
            }, function (index) {
                data.elem.checked = !data.elem.checked;
                form.render();
                layer.close(index);
            });
        }
    });

    function del(managerId) {
        $.ajax({
            type: 'POST',
            url: '/Manager/Delete/',
            data: { managerId: managerId },
            dataType: "json",
            headers: {
                "X-CSRF-TOKEN-yilezhu": $("input[name='AntiforgeryKey_yilezhu']").val()
            },
            success: function (data) {//res为相应体,function为回调函数
                var index = layer.msg(data.ResultMsg, {
                    time: 2000 //20s后自动关闭
                }, function () {
                    tableIns.reload();
                    layer.close(index);
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
            }
        });
    }
    ///用户重申 重置用户
    function resetApply(managerId)
    {
        if (isAdmin) {

            $.ajax({
                type: 'POST',
                url: '/Manager/ResetPushLink/',
                data: { managerId: managerId },
                dataType: "json",
                headers: {
                    "X-CSRF-TOKEN-yilezhu": $("input[name='AntiforgeryKey_yilezhu']").val()
                },
                success: function (data) {//res为相应体,function为回调函数
                    if (data.ResultCode == 200) {
                        layer.alert(data.Data);
                    }

                    //var index = layer.msg(data.ResultMsg, {
                    //    time: 2000 //20s后自动关闭
                    //}, function () {
                    //    //tableIns.reload();
                    //    layer.close(index);
                    //});
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
                }
            });
        }

    }
    function resetpwd(managerId) {
        $.ajax({
            type: 'POST',
            url: '/Manager/ResetPassword/',
            data: { managerId: managerId },
            dataType: "json",
            headers: {
                "X-CSRF-TOKEN-yilezhu": $("input[name='AntiforgeryKey_yilezhu']").val()
            },
            success: function (data) {//res为相应体,function为回调函数
                var index = layer.msg(data.ResultMsg, {
                    time: 2000 //20s后自动关闭
                }, function () {
                    //tableIns.reload();
                    layer.close(index);
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
            }
        });
    }

    

    function changeLockStatus(managerId, status) {
        $.ajax({
            type: 'POST',
            url: '/Manager/ChangeLockStatus/',
            data: { Id: managerId, IsLock: status },
            dataType: "json",
            headers: {
                "X-CSRF-TOKEN-yilezhu": $("input[name='AntiforgeryKey_yilezhu']").val()
            },
            success: function (data) {//res为相应体,function为回调函数
                layer.msg(data.ResultMsg);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
            }
        });
    }

    function mycode() {
        $.ajax({
            type: 'POST',
            url: '/Manager/MyCode/',
            data: {},
            dataType: "json",
            headers: {
                "X-CSRF-TOKEN-yilezhu": $("input[name='AntiforgeryKey_yilezhu']").val()
            },
            success: function (data) {//res为相应体,function为回调函数
                var msg = data.ResultMsg;
                layer.alert(msg, { icon: 1, title: "我的推荐码" });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
            }
        });
    }

    function copyToClipboard(txt) {
        var window = top.window;

        if (window.clipboardData) {
            window.clipboardData.clearData();
            clipboardData.setData("Text", txt);
            window.alert("复制成功！");
        } else if (navigator.userAgent.indexOf("Opera") != -1) {
            window.location = txt;
        } else if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            } catch (e) {
                window.alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将 'signed.applets.codebase_principal_support'设置为'true'");
            }
            var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
            if (!clip)
                return;
            var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
            if (!trans)
                return;
            trans.addDataFlavor("text/unicode");
            var str = new Object();
            var len = new Object();
            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
            var copytext = txt;
            str.data = copytext;
            trans.setTransferData("text/unicode", str, copytext.length * 2);
            var clipid = Components.interfaces.nsIClipboard;
            if (!clip)
                return false;
            clip.setData(trans, null, clipid.kGlobalClipboard);
            window.alert("复制成功！");
        }
    }

    // 确认审核逻辑
    function confirm_audit(data) {
        if (isAdmin) {
            // 只有营业厅可以操作
            layer.confirm('你确认要审核通过吗？', {
                icon: 3,
                title: '审核提示',
                btn: ['通过', '不通过', '取消'],
                btn3: function (index, layero) {
                    layer.close(index);
                },
                cancel: function (index) {
                    layer.close(index);
                }
            },
                function (index) {
                    ///通过
                    audit(data.Id, 1);
                    layer.close(index);
                },
                function (index) {
                    //审核不通过
                    //audit(data.Id, 2);
                    settingAuditRemark(data.Id);
                    layer.close(index);
                });
        }
    }
    //审核
    function audit(id, state) {
        $.ajax({
            type: 'POST',
            url: '/Manager/Audit/',
            data: {
                Id: id,
                State: state
            },
            dataType: "json",
            headers: {
                "X-CSRF-TOKEN-yilezhu": $("input[name='AntiforgeryKey_yilezhu']").val()
            },
            success: function (data) {//res为相应体,function为回调函数
                var alertIndex = layer.alert(data.ResultMsg, { icon: 3 }, function () {
                    layui.table.reload('managerListTable', {
                        where: {}
                        , page: {
                            curr: 1 //重新从第 1 页开始
                        }
                    });
                    top.layer.close(alertIndex);
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
            }
        });
    }

    // 手续费设置
    function settingTrade(managerId) {
        var index = layui.layer.open({
            title: '手续费设置',
            type: 2,
            anim: 1,
            area: ['900px', '90%'],
            content: "/TradeCommission/SettingUserTrade?managerId=" + managerId,
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (managerId) {
                    //body.find("#Id").val(edit.Id);
                    form.render();
                }
            }
        });
    }
    ///驳回备注信息
    function settingAuditRemark(managerId) {
        var index3 =  layui.layer.open({
            title: '驳回原因',
            area: ['500px', '50%'],
            anim:1,
            content: "<textarea style='height:70%;width:420px;padding:20px;' name='audit_remark' placeholder='请输入原因'></textarea>",
            yes:function(index,layero){

                $.ajax({
                    type: 'POST',
                    url: '/Manager/AuditRejectRemark/',
                    data: {
                        managerId: managerId,
                        auditRemark: $("textarea[name='audit_remark']").val()
                    },
                    dataType: "json",
                    headers: {
                        "X-CSRF-TOKEN-yilezhu": $("input[name='AntiforgeryKey_yilezhu']").val()
                    },
                    success: function (data) {//res为相应体,function为回调函数
                        var index2 = layer.msg(data.ResultMsg, {
                            time: 2000 //2s后自动关闭
                        }, function () {
                            tableIns.reload();
                            layui.layer.close(index);
                        });
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
                    }
                });

            }
            
        });
    }

});
